package com.inetools.gwetons.client.timer;

import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.GWT.UncaughtExceptionHandler;

/**
 * TimeredCracker class holds the triggered part by com.inetools.gwetons.client.TimerSingletonController 
 * when interval elapse.
 * @author ay
 */
public class TimeredCracker {
	public interface TimerSingletonControllerAttacher {
		public void fire();
		public void remove();
	}
	protected final TimerSingletonControllerAttacher timerSingletonControllerAttacher;
	
	protected final boolean forRepeat;
	public boolean isForRepeat() {
		return forRepeat;
	}

	public TimeredCracker( 
			boolean forRepeat, 
			TimerSingletonControllerAttacher timerSingletonControllerAttacher) {
		this.forRepeat = forRepeat;
		this.timerSingletonControllerAttacher = timerSingletonControllerAttacher;
	}

	private void fireImpl() {
		// If this is a one-shot timer, remove it from the timer list. 
		if ( !forRepeat && ( timerSingletonControllerAttacher != null)) {
			timerSingletonControllerAttacher.remove();
		}
	
		// Run the timer's code.
		timerSingletonControllerAttacher.fire();
	} // private void fireImpl()
	
	private void fireAndCatch( UncaughtExceptionHandler handler) {
		try {
			fireImpl();
		} catch (Throwable e) {
			handler.onUncaughtException(e);
		}
	} // private void fireAndCatch( UncaughtExceptionHandler handler)

	/*
	 * Via either createInterval method or createTimeout method 
	 * in com.inetools.gwetons.client.TimerSingletonController class, 
	 * called by native code when this timer fires.
	 */
	public final void fire() {
		UncaughtExceptionHandler handler = GWT.getUncaughtExceptionHandler();
		if (handler != null) {
			fireAndCatch(handler);
		} 
		else {
			fireImpl();
		}
	} // public final void fire()
}
